var SAGE = SAGE || {};
SAGE.Ajax = SAGE.Ajax ||{};
SAGE.Environment = SAGE.Environment || {};
SAGE.Form = SAGE.Form || {};

/**
 * Use Ajax to get an html snippet. 
 * By Default, it is asynchronous.
 * 
 * @param selector
 * @param url
 * @param callback_opt
 * @param async_opt
 * @param params_opt
 */
SAGE.Ajax.getHtml = function(selector, url, callback_opt, async_opt, params_opt){
	jQuery.ajax({
		"url" : url,
		"type" : "GET",
		"dataType": "html",
		"async" : (async_opt == undefined ? true : async_opt),
		"data" : params_opt
	}).done(function(rText){
		$(selector).html(rText);
		if(callback_opt){
			callback_opt(rText);
		}
	}).fail(function(){
		console.error("url["+url+"]");
	});
};


/**
 * Use Ajax to get a json. 
 * By Default, it is asynchronous.
 * 
 * @param url
 * @param callback_opt
 * @param async_opt
 * @param params_opt
 */
SAGE.Ajax.getJson = function(url, callback_opt, async_opt, params_opt){
	jQuery.ajax({
		"url" : url,
		"type" : "GET",
		"dataType": "json",
		"async" : (async_opt == undefined ? true : async_opt),
		"data" : params_opt
	}).done(function(rText){
		if(callback_opt){
			callback_opt(rText);
		}
	}).fail(function(){
		console.error("url["+url+"]");
	});
};

SAGE.Ajax.createLoading = function($sel){
	var offset = $sel.offset();
	var width = $sel.innerWidth();
	var height = $sel.innerHeight();
	var $loadingDiv = $(SAGE.Environment.loadingHTML);
	$(document.body).append($loadingDiv);
	$loadingDiv.css({
		"position":"absolute",
		"z-index" : "999",
		"left": offset.left + "px",
		"top" : offset.top + "px",
		"width": width + "px",
		"height": height + "px",
		"display": "block"
	});
	return $loadingDiv;
};

SAGE.Environment.libRoot = $("script").last().attr("src").replace(new RegExp("\\\\","gm"), "/");
SAGE.Environment.loadingHTML = "";
$(document.body).ready(function(){
	var templateURL = SAGE.Environment.libRoot.substring(0, SAGE.Environment.libRoot.lastIndexOf("/")+1) + "master_template/";
	SAGE.Ajax.getHtml(null, templateURL + "header_footer_template.html", function(rText){
		var $tempNode = $(document.createElement("TEMP"));
		$tempNode.html(rText);
		//Render Fixed Top Nav bar
		if($(".page-body .page-container header.navbar.navbar-fixed-top").length>0){
			$(".page-body .page-container header.navbar.navbar-fixed-top").html($tempNode.find("#tmpl_page_header").html());
		}
		
		if($(".page-body .page-container .sidebar-menu").length!=0){
			//Render Fixed Left Nav Bar
			$(".page-body .page-container .sidebar-menu").html($tempNode.find("#tmpl_page_sidebar").html());
			//Apend Show/Hide Event
			setup_sidebar_menu();
			$(".sidebar-collapse-icon.with-animation").bind("click", function(){
				toggle_sidebar_menu(true);
			});

			$(".main-content").prepend($tempNode.find("#tmpl_page_userinfo").html());
		}
		

		var $footer = $("<footer class='main'></footer>");
		$footer.html($tempNode.find("#tmpl_page_footer").html());
		$(".page-body .page-container .main-content").append($footer);
		
		//LOADING HTML Snippet
		SAGE.Environment.loadingHTML = $tempNode.find("#ajax-loading-tmpl").html();
	}, false);
	
});


//SAGE.FormUtil
//DECORATOR
SAGE.Form.decorateSlider = function(){
	$(".slider").each(function(i, el)
			{
				var $this = $(el),
					$label_1 = $('<span class="ui-label"></span>'),
					$label_2 = $label_1.clone(),
					
					orientation = attrDefault($this, 'vertical', 0) != 0 ? 'vertical' : 'horizontal',
					
					prefix = attrDefault($this, 'prefix', ''),
					postfix = attrDefault($this, 'postfix', ''),
					
					fill = attrDefault($this, 'fill', ''),
					$fill = $(fill),
					
					step = attrDefault($this, 'step', 1),
					value = attrDefault($this, 'value', 5),
					min = attrDefault($this, 'min', 0),
					max = attrDefault($this, 'max', 100),
					min_val = attrDefault($this, 'min-val', 10),
					max_val = attrDefault($this, 'max-val', 90),
					
					is_range = $this.is('[data-min-val]') || $this.is('[data-max-val]'),
					
					reps = 0;
				
				
				// Range Slider Options
				if(is_range)
				{
					$this.slider({
						range: true,
						orientation: orientation,
						min: min,
						max: max,
						values: [min_val, max_val],
						step: step,
						slide: function(e, ui)
						{
							var opts = $this.data('uiSlider').options,
								min_val = (prefix ? prefix : '') + ui.values[0] + (postfix ? postfix : ''),
								max_val = (prefix ? prefix : '') + ui.values[1] + (postfix ? postfix : '');
							
							$label_1.html( min_val );
							$label_2.html( max_val );
							
							if(fill)
								$fill.val(min_val + ',' + max_val);
								
							reps++;
						},
						change: function(ev, ui)
						{
							if(reps == 1)
							{
								var opts = $this.data('uiSlider').options,
									min_val = (prefix ? prefix : '') + ui.values[0] + (postfix ? postfix : ''),
									max_val = (prefix ? prefix : '') + ui.values[1] + (postfix ? postfix : '');
								
								$label_1.html( min_val );
								$label_2.html( max_val );
								
								if(fill)
									$fill.val(min_val + ',' + max_val);
							}
							
							reps = 0;
						}
					});
				
					var $handles = $this.find('.ui-slider-handle');
						
					$label_1.html((prefix ? prefix : '') + min_val + (postfix ? postfix : ''));
					$handles.first().append( $label_1 );
					
					$label_2.html((prefix ? prefix : '') + max_val+ (postfix ? postfix : ''));
					$handles.last().append( $label_2 );
				}
				// Normal Slider
				else
				{	
					
					$this.slider({
						range: attrDefault($this, 'basic', 0) ? false : "min",
						orientation: orientation,
						min: min,
						max: max,
						value: value,
						step: step,
						slide: function(ev, ui)
						{
							var opts = $this.data('uiSlider').options,
								val = (prefix ? prefix : '') + opts.value + (postfix ? postfix : '');
							
							$label_1.html( val );
							
							if(fill)
								$fill.val(val);
							
							reps++;
						},
						change: function(ev, ui)
						{
							if(reps == 1)
							{
								var opts = $this.data('uiSlider').options,
									val = (prefix ? prefix : '') + opts.value + (postfix ? postfix : '');
								
								$label_1.html( val );
								
								if(fill)
									$fill.val(val);
							}
							
							reps = 0;
						}
					});
					
					var $handles = $this.find('.ui-slider-handle');
						//$fill = $('<div class="ui-fill"></div>');
					
					$label_1.html((prefix ? prefix : '') + value + (postfix ? postfix : ''));
					$handles.html( $label_1 );
					
					//$handles.parent().prepend( $fill );
					
					//$fill.width($handles.get(0).style.left);
				}
				
			})
};



SAGE.Form.parseFormToJson = function($sel) {
	var pojo_list = $sel.find("[pojo-bind]");
	var result = {};
	for (var i = 0; i < pojo_list.length; i++) {
		var $elem = $(pojo_list[i]), 
			attr = $elem.attr("pojo-bind"), 
			tagName = pojo_list[i].tagName.toLowerCase(), 
			type = ($elem.attr("type") !=null ? $elem.attr("type") : "").toLowerCase();
		
		if (tagName == "input" && type == "text" && $elem.hasClass("datepicker")) {
			result[attr] = new Date($elem.val());
		}
		else if(tagName == "input" && type == "text"){
			result[attr] = $elem.val();
		}
		else if(tagName == "input" && type =="checkbox"){
			result[attr] = $elem.attr("checked") != null;
		}
		else if(tagName == "select"){
			result[attr] = $elem.val();
		}
		else if(tagName == "div" && $elem.hasClass("slider")){
			var labels = $elem.find(".ui-label");
			if(labels.length == 1){
				result[attr] = parseInt(labels[0].innerHTML);
			}
			else{
				result[attr] = [parseInt(labels[0].innerHTML), parseInt(labels[1].innerHTML)];
			}
		}
		else if(tagName == "textarea"){
			var $iframe = $elem.siblings("iframe.wysihtml5-sandbox");
			if($iframe >0){
				result[attr] = $iframe.contents()[0].body.innerHTML;
			}
			else{
				result[attr] = $elem.val();
			}
		}
	}
	return result;
};


